package com.sq.loginservice.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.sq.api.user.model.LoginUser;
import com.sq.common.constants.Constants;
import com.sq.common.utils.request.RequestUtil;
import com.sq.common.web.domain.AjaxResult;
import com.sq.loginservice.dto.LoginDto;
import com.sq.loginservice.service.LoginService;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

/**
 * @Author Li sir
 * @Date 2024/9/24
 */

@RestController
@RequestMapping("/api/login/")
public class LoginController {

    @Autowired
    private LoginService loginService;


    @RequestMapping("login")
    public AjaxResult login(@RequestBody LoginDto loginDto){
        LoginUser loginUser = loginService.login(loginDto.getUsername(), loginDto.getPassword());
        //  添加tocker
        StpUtil.login(loginUser.getUserid());
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();

        HashMap<String, String> tokenMap = new HashMap<>();
        tokenMap.put(Constants.tokenName,tokenInfo.getTokenName());
        tokenMap.put(Constants.tokenValue,tokenInfo.getTokenValue());

        loginUser.setSysUser(null);
        loginUser.setToken(tokenMap);

        return AjaxResult.success("登录成功",loginUser);
    }

    @RequestMapping("isLogin")
    public SaResult isLogin(String loginId) {
        boolean result = false;
        if (StringUtils.isBlank(loginId)){
            result = StpUtil.isLogin();
        }else {
            result = StpUtil.isLogin(loginId);
        }
        return SaResult.ok("登录状态是:"+result);
    }

    @RequestMapping("loginout")
    public AjaxResult loginOut(@RequestBody LoginDto loginDto){
        loginService.loginOut(loginDto.getUsername());
        return AjaxResult.success();
    }



}
